import os
import time
import platform
import psutil
from datetime import datetime, timedelta
from flask import Blueprint, jsonify, current_app
from ..api.auth import login_required

system_bp = Blueprint('system', __name__)

start_time = time.time()

# 系统事件记录
system_events = [
    {'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 'message': '系统启动成功', 'type': 'info'},
]

# 下载和上传统计
download_count = {'total': 0, 'today': 0}
upload_count = {'total': 0, 'today': 0}
last_reset_date = datetime.now().date()

def add_system_event(message, event_type='info'):
    """添加系统事件"""
    global system_events
    system_events.append({
        'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'message': message,
        'type': event_type
    })
    # 保持事件列表不超过100条
    if len(system_events) > 100:
        system_events = sorted(system_events, key=lambda x: x['timestamp'], reverse=True)[:100]

def record_download(filename, ip):
    """记录文件下载"""
    global download_count
    check_reset_counters()  # 检查是否需要重置今日计数
    download_count['total'] += 1
    download_count['today'] += 1
    # 简化文件名显示，如果太长就截断
    display_name = filename if len(filename) <= 20 else filename[:17] + "..."
    add_system_event(f'下载: {display_name}', 'download')

def record_upload(filename, ip):
    """记录文件上传"""
    global upload_count
    check_reset_counters()  # 检查是否需要重置今日计数
    upload_count['total'] += 1
    upload_count['today'] += 1
    # 简化文件名显示，如果太长就截断
    display_name = filename if len(filename) <= 20 else filename[:17] + "..."
    add_system_event(f'上传: {display_name}', 'upload')

def check_reset_counters():
    """检查是否需要重置今日计数"""
    global last_reset_date, download_count, upload_count
    today = datetime.now().date()
    if today > last_reset_date:
        download_count['today'] = 0
        upload_count['today'] = 0
        last_reset_date = today

@system_bp.route('/status')
@login_required
def system_status():
    uptime = int(time.time() - start_time)
    uptime_hours, remainder = divmod(uptime, 3600)
    uptime_minutes, uptime_seconds = divmod(remainder, 60)
    
    # 获取系统负载
    try:
        load_avg = [x / psutil.cpu_count() * 100 for x in psutil.getloadavg()]
        cpu_percent = psutil.cpu_percent(interval=0.1)
        memory = psutil.virtual_memory()
    except:
        # 如果无法获取系统信息，使用默认值
        load_avg = [0.0, 0.0, 0.0]
        cpu_percent = 0.0
        memory = {'percent': 0, 'total': 0, 'used': 0, 'free': 0}
    
    return jsonify({
        'status': 'running',
        'uptime': uptime,
        'uptime_formatted': f"{uptime_hours}小时 {uptime_minutes}分钟 {uptime_seconds}秒",
        'load': {
            'current': f"{load_avg[0]:.2f}",
            'cpu_percent': cpu_percent
        },
        'memory': {
            'percent': memory.percent,
            'total': memory.total,
            'used': memory.used,
            'free': memory.free
        },
        'system_info': {
            'platform': platform.system(),
            'version': platform.version(),
            'hostname': platform.node()
        }
    })

@system_bp.route('/stats')
@login_required
def system_stats():
    upload_dir = current_app.config['UPLOAD_FOLDER']
    total_size = 0
    total_files = 0
    file_types = {}
    
    # 检查是否需要重置今日计数
    check_reset_counters()
    
    # 统计文件信息
    if os.path.exists(upload_dir):
        for filename in os.listdir(upload_dir):
            file_path = os.path.join(upload_dir, filename)
            if os.path.isfile(file_path):
                total_size += os.path.getsize(file_path)
                total_files += 1
                
                # 统计文件类型
                file_ext = os.path.splitext(filename)[1].lower()
                if file_ext:
                    file_types[file_ext] = file_types.get(file_ext, 0) + 1
                else:
                    file_types['other'] = file_types.get('other', 0) + 1
    
    # 获取存储信息
    try:
        disk = psutil.disk_usage(upload_dir)
    except:
        disk = {'total': 1000000000, 'used': total_size, 'free': 1000000000 - total_size, 'percent': 0}
    
    # 将文件类型转换为饼图数据格式
    file_type_data = [
        {'name': 'PDF', 'value': file_types.get('.pdf', 0)},
        {'name': 'DOC/DOCX', 'value': file_types.get('.doc', 0) + file_types.get('.docx', 0)},
        {'name': 'XLS/XLSX', 'value': file_types.get('.xls', 0) + file_types.get('.xlsx', 0)},
        {'name': 'PPT/PPTX', 'value': file_types.get('.ppt', 0) + file_types.get('.pptx', 0)},
        {'name': '其他', 'value': sum(v for k, v in file_types.items() if k not in ['.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'])}
    ]
    
    return jsonify({
        'storage': {
            'total': disk.total,
            'used': disk.used,
            'free': disk.free,
            'percent': disk.percent,
            'total_formatted': f"{disk.total / (1024*1024*1024):.2f} GB",
            'used_formatted': f"{disk.used / (1024*1024*1024):.2f} GB",
            'free_formatted': f"{disk.free / (1024*1024*1024):.2f} GB"
        },
        'files': {
            'total': total_files,
            'total_size': total_size,
            'total_size_formatted': f"{total_size / (1024*1024):.2f} MB",
            'today_uploads': upload_count['today'],
            'today_downloads': download_count['today'],
            'total_uploads': upload_count['total'],
            'total_downloads': download_count['total'],
            'file_types': file_type_data
        }
    })

@system_bp.route('/events')
@login_required
def get_system_events():
    global system_events
    # 只返回最近10条事件
    events = sorted(system_events, key=lambda x: x['timestamp'], reverse=True)[:10]
    # 简化时间戳格式
    for event in events:
        try:
            dt = datetime.strptime(event['timestamp'], '%Y-%m-%d %H:%M:%S')
            event['timestamp'] = dt.strftime('%H:%M:%S')
        except:
            pass
    return jsonify(events) 